package org.fatmansoft.teach.controllers;

import org.apache.poi.ss.formula.functions.T;
import org.fatmansoft.teach.models.*;
import org.fatmansoft.teach.payload.request.DataRequest;
import org.fatmansoft.teach.payload.response.DataResponse;
import org.fatmansoft.teach.repository.*;
import org.fatmansoft.teach.service.OtherService;
import org.fatmansoft.teach.util.ComDataUtil;
import org.fatmansoft.teach.util.CommonMethod;
import org.fatmansoft.teach.util.DateTimeTool;
import org.fatmansoft.teach.util.JsonConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/other")

public class OtherController {
    @Autowired
    private PersonRepository personRepository;  //人员数据操作自动注入
    @Autowired
    private OtherRepository otherRepository;  //学生数据操作自动注入
    @Autowired
    private UserRepository userRepository;  //学生数据操作自动注入

    @Autowired
    private OtherService otherService;
    @Autowired
    private UserTypeRepository userTypeRepository; //用户类型数据操作自动注入
    @Autowired
    private PasswordEncoder encoder;  //密码服务自动注入

    @PostMapping("/getOtherList")
    public String  getOtherList(@Valid @RequestBody DataRequest dataRequest) {
        String numName = dataRequest.getString("numName");
        if(numName == null)
            numName ="";
        List<Other> sList = otherRepository.findOtherListByNumName(numName);
        return JsonConvertUtil.getDataListJson(sList);
    }



    @PostMapping("/otherDelete")
    public DataResponse otherDelete(@Valid @RequestBody DataRequest dataRequest) {
        Integer otherId = dataRequest.getInteger("otherId");  //获取other_id值
        Other s = null;
        Optional<Other> op;
        if (otherId != null) {
            op = otherRepository.findById(otherId);   //查询获得实体对象
            if (op.isPresent()) {
                s = op.get();
            }
        }
        if (s != null) {
            otherRepository.delete(s);    //首先数据库永久删除学生信息
        }
        return CommonMethod.getReturnMessageOK();  //通知前端操作正常
    }

    /**
     * getOtherInfo 前端点击学生列表时前端获取学生详细信息请求服务
     *
     * @param dataRequest 从前端获取 otherId 查询学生信息的主键 other_id
     * @return 根据otherId从数据库中查出数据，存在Map对象里，并返回前端
     */

    @PostMapping("/getOtherInfo")
    public String getOtherInfo(@Valid @RequestBody DataRequest dataRequest) {
        Integer otherId = dataRequest.getInteger("otherId");
        Other s = null;
        Optional<Other> op;
        if (otherId != null) {
            op = otherRepository.findById(otherId); //根据学生主键从数据库查询学生的信息
            if (op.isPresent()) {
                s = op.get();
            }
        }
        if(s == null) {
            s = new Other();
            s.setPerson(new Person());
        }
        return JsonConvertUtil.getDataObjectJson(s);
    }

    @PostMapping("/otherEditSave")
    public DataResponse otherEditSave(@Valid @RequestBody DataRequest dataRequest) {
        Integer otherId = dataRequest.getInteger("otherId");
        Map form = dataRequest.getMap("form"); //参数获取Map对象
        Map pForm =  CommonMethod.getMap(form,"person");
        String num = CommonMethod.getString(pForm, "num");  //Map 获取属性的值
        Other s = null;
        Person p;
        User u;
        Optional<Other> op;
        Integer personId;
        if (otherId != null) {
            op = otherRepository.findById(otherId);  //查询对应数据库中主键为id的值的实体对象
            if (op.isPresent()) {
                s = op.get();
            }
        }
        Optional<Person> nOp = personRepository.findByNum(num); //查询是否存在num的人员
        if (!nOp.isPresent()) {
            return CommonMethod.getReturnMessageError("该工号不存在，不能添加或修改！");
        }//防止人通过添加其他信息添加了一个新的成员
        else{
            if (s == null || !s.getPerson().getNum().equals(num)) {
                return CommonMethod.getReturnMessageError("新工号已经存在，不能添加或修改！");
            }
        }//防止人给一个人添加多个信息，保证是一对一
        if (s == null) {//添加功能
            s = new Other();   // 创建实体对象
            p = s.getPerson();
            s.setPerson(p);
            otherRepository.saveAndFlush(s);  //插入新的Other记录
        } else {//修改功能
            p = s.getPerson();
        }
        personId = p.getPersonId();
        if (!num.equals(p.getNum())) {   //如果人员编号变化，修改人员编号和登录账号
            Optional<User> uOp = userRepository.findByPersonPersonId(personId);
            if (uOp.isPresent()) {
                u = uOp.get();
                u.setUserName(num);
                userRepository.saveAndFlush(u);
            }
            p.setNum(num);  //设置属性
        }
        s.setPrimarySchool(CommonMethod.getString(pForm, "primarySchool"));
        s.setJunior(CommonMethod.getString(pForm, "junior"));
        s.setSenior(CommonMethod.getString(pForm, "senior"));
        otherRepository.save(s);  //修改保存学生信息
        return CommonMethod.getReturnData(s.getOtherId());  // 将otherId返回前端
    }
    @PostMapping("/getOtherPageData")
    public DataResponse getOtherPageData(@Valid @RequestBody DataRequest dataRequest) {
        String numName = dataRequest.getString("numName");
        Integer cPage = dataRequest.getCurrentPage();
        int dataTotal = 0;
        int size = 40;
        List dataList = new ArrayList();
        Page<Other> page = null;
        Pageable pageable = PageRequest.of(cPage, size);
        page = otherRepository.findOtherPageByNumName(numName, pageable);
        Map m;
        Other s;
        if (page != null) {
            dataTotal = (int) page.getTotalElements();
            List list = page.getContent();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    s = (Other) list.get(i);
                    m = otherService.getMapFromOther(s);
                    dataList.add(m);
                }
            }
        }
        HashMap data = new HashMap();
        data.put("dataTotal", dataTotal);
        data.put("pageSize", size);
        data.put("dataList", dataList);
        return CommonMethod.getReturnData(data);
    }
}
